@using ThridGroup.ERP.DTO
@using ThridGroup.ERP.ProductionSystem
@{
    ViewData["Title"] = "物料分类管理";
    Layout = null;
}
@Html.AntiForgeryToken()

<script src="~/libs/scripts/jquery-3.4.1.min.js"></script>
<link href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>

<style>
    .search-box {
        background-color: #fff;
        padding: 20px;
        margin-bottom: 10px;
    }
    .search-box .layui-inline {
        margin-right: 10px;
    }
    .search-box input.layui-input {
        width: 200px;
    }
    .btn-add {
        float: right;
        background-color: #1890ff;
    }
    .material-list {
        background-color: #fff;
        padding: 20px;
    }
    .layui-table-cell .layui-btn + .layui-btn {
        margin-left: 5px;
    }
    .layui-table {
        width: 100%;
        background: #fff;
        margin-top: 10px;
    }
    .layui-table th {
        background: #f5f7fa;
        color: #333;
        font-weight: 600;
        padding: 14px 10px;
        border-bottom: 1.5px solid #eaeaea;
        text-align: left;
    }
    .layui-table td {
        padding: 12px 10px;
        border-bottom: 1px solid #f0f0f0;
        color: #444;
    }
    .layui-table tbody tr:hover {
        background: #f0f7ff;
    }
    .layui-table-cell .layui-btn-sm {
        height: 28px;
        line-height: 28px;
        padding: 0 10px;
        font-size: 12px;
        margin: 2px 4px;
    }
    .layui-btn-normal { background-color: #1E9FFF; }
    .layui-btn-danger { background-color: #FF5722; }
    .layui-btn-warm { background-color: #FFB800; }
    .layui-table-cell {
        height: auto;
        line-height: 28px;
    }
    .tree-table-indent {
        padding-left: 20px;
    }
    .tree-table-icon {
        margin-right: 5px;
    }
</style>

<div class="search-box">
    <form class="layui-form" lay-filter="searchForm">
        <div class="layui-inline">
            <input type="text" name="materialTypeName" placeholder="分类名称" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-inline">
            <select name="isEnable" lay-filter="isEnable">
                <option value="">全部</option>
                <option value="true">启用</option>
                <option value="false">禁用</option>
            </select>
        </div>
        <div class="layui-inline">
            <button class="layui-btn" lay-submit lay-filter="searchBtn">
                <i class="layui-icon">&#xe615;</i> 搜索
            </button>
            <button type="reset" class="layui-btn layui-btn-primary">
                <i class="layui-icon">&#xe669;</i> 重置
            </button>
        </div>
        <button type="button" class="layui-btn btn-add" id="btnAdd">
            <i class="layui-icon">&#xe654;</i> 新增分类
        </button>
    </form>
</div>

<div class="material-list">
    <table id="materialTypeTable" lay-filter="materialTypeTable"></table>
</div>

<!-- 编辑表单模板 -->
<script type="text/html" id="editForm">
    <form class="layui-form" lay-filter="materialTypeForm" style="padding: 20px;" onsubmit="return false;">
        @Html.AntiForgeryToken()
        <input type="hidden" name="Id" value="0">
        <input type="hidden" name="ParentId" value="0">
        <input type="hidden" name="IsDeleted" value="false">
        
        <div class="layui-form-item">
            <label class="layui-form-label required">分类名称</label>
            <div class="layui-input-block">
                <input type="text" name="MaterialTypeName" lay-verify="required" lay-reqtext="分类名称不能为空" placeholder="请输入分类名称" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label required">排序</label>
            <div class="layui-input-block">
                <input type="number" name="Index" lay-verify="required|number" lay-reqtext="排序不能为空" placeholder="请输入排序" value="0" class="layui-input">
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label">是否启用</label>
            <div class="layui-input-block">
                <input type="checkbox" name="IsEnable" lay-skin="switch" lay-text="是|否">
            </div>
        </div>
        
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" lay-submit lay-filter="submitForm">确定</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</script>

<!-- 表格操作列模板 -->
<script type="text/html" id="tableToolbar">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="edit">
            <i class="layui-icon">&#xe642;</i> 编辑
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">
            <i class="layui-icon">&#xe640;</i> 删除
        </button>
        <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="addChild">
            <i class="layui-icon">&#xe654;</i> 添加子分类
        </button>
    </div>
</script>

<script>
    layui.use(['table', 'form', 'layer'], function () {
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.$;

        // 初始化表格
        function renderTable(where) {
            table.render({
                elem: '#materialTypeTable',
                url: '/MaterialType/GetMaterialTypes',
                method: 'get',
                where: where || {},
                toolbar: '#toolbarDemo',
                defaultToolbar: ['filter', 'print', 'exports'],
                parseData: function(res) {
                    if (res.code === 0 && res.data) {
                        var treeData = convertToTree(res.data);
                        return {
                            "code": 0,
                            "msg": res.msg,
                            "count": treeData.length,
                            "data": treeData
                        };
                    }
                    return res;
                },
                cols: [[
                    { 
                        field: 'materialTypeName', 
                        title: '分类名称', 
                        width: '30%',
                        templet: function(d) {
                            var indent = getIndent(d.level || 0);
                            var icon = d.children && d.children.length > 0 ? 
                                '<i class="layui-icon layui-icon-triangle-d tree-table-icon"></i>' : 
                                '<i class="layui-icon layui-icon-file tree-table-icon"></i>';
                            return indent + icon + d.materialTypeName;
                        }
                    },
                    { 
                        field: 'isEnable', 
                        title: '是否启用', 
                        width: '15%',
                        align: 'center',
                        templet: function(d) {
                            return '<span style="color: ' + (d.isEnable ? '#009688' : '#FF5722') + ';">' + 
                                   (d.isEnable ? '是' : '否') + '</span>';
                        }
                    },
                    { 
                        field: 'index', 
                        title: '排序', 
                        width: '10%',
                        align: 'center'
                    },
                    { 
                        field: 'createTime', 
                        title: '创建时间',
                        width: '20%',
                        align: 'center',
                        templet: function(d) {
                            return d.createTime ? layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss') : '';
                        }
                    },
                    {
                        title: '操作',
                        width: '25%',
                        align: 'center',
                        toolbar: '#tableToolbar',
                        fixed: 'right'
                    }
                ]],
                done: function(res) {
                    console.log('表格渲染完成:', res);
                }
            });
        }

        // 将平级数据转换为树形结构
        function convertToTree(data) {
            var map = {};
            var treeData = [];
            
            // 第一步：建立映射关系
            data.forEach(function(item) {
                map[item.id] = item;
                item.children = [];
                item.level = 0;
            });
            
            // 第二步：构建树形结构
            data.forEach(function(item) {
                if (item.parentId && map[item.parentId]) {
                    var parent = map[item.parentId];
                    item.level = (parent.level || 0) + 1;
                    parent.children.push(item);
                } else {
                    treeData.push(item);
                }
            });
            
            // 第三步：展开树形数据为表格数据
            return flattenTree(treeData);
        }

        // 展开树形数据为表格数据
        function flattenTree(treeData) {
            var result = [];
            
            function flatten(items, level) {
                items.forEach(function(item) {
                    item.level = level;
                    result.push(item);
                    if (item.children && item.children.length > 0) {
                        flatten(item.children, level + 1);
                    }
                });
            }
            
            flatten(treeData, 0);
            return result;
        }

        // 获取缩进空格
        function getIndent(level) {
            var space = '';
            for (var i = 0; i < level; i++) {
                space += '<span class="tree-table-indent"></span>';
            }
            return space;
        }

        // 初始化表格
        renderTable();

        // 搜索按钮点击事件
        form.on('submit(searchBtn)', function(data) {
            var formData = data.field;
            var searchParams = {
                materialTypeName: formData.materialTypeName || '',
                isEnable: formData.isEnable === 'true' ? true : 
                         formData.isEnable === 'false' ? false : null
            };
            renderTable(searchParams);
            return false;
        });

        // 重置按钮点击事件
        $('button[type="reset"]').click(function() {
            form.val('searchForm', {
                'materialTypeName': '',
                'isEnable': ''
            });
            form.render('select');
            renderTable();
        });

        // 监听工具条事件
        table.on('tool(materialTypeTable)', function(obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                openEditForm(data);
            } else if (obj.event === 'delete') {
                layer.confirm('确定要删除此分类吗？', {
                    title: '删除确认',
                    btn: ['确定','取消']
                }, function(index) {
                    deleteType(data.id, index);
                });
            } else if (obj.event === 'addChild') {
                openEditForm(null, data.id);
            }
        });

        // 删除分类
        function deleteType(id, index) {
            var antiForgeryToken = $('input[name="__RequestVerificationToken"]').val();
            
            $.ajax({
                url: '/MaterialType/DeleteMaterialType',
                type: 'POST',
                traditional: true,
                data: {
                    'id': id,
                    '__RequestVerificationToken': antiForgeryToken
                },
                beforeSend: function() {
                    layer.load(2);
                },
                success: function(res) {
                    layer.closeAll('loading');
                    if (res.code === 0) {
                        layer.close(index);
                        layer.msg('删除成功');
                        renderTable();
                    } else {
                        layer.msg(res.msg || '删除失败');
                    }
                },
                error: function(xhr) {
                    layer.closeAll('loading');
                    layer.msg('操作失败，请重试');
                }
            });
        }

        // 打开编辑表单
        function openEditForm(data, parentId) {
            var title = data ? '编辑分类' : '新增分类';
            layer.open({
                type: 1,
                title: title,
                content: $('#editForm').html(),
                area: ['500px', '400px'],
                success: function(layero, index) {
                    form.render(null, 'materialTypeForm');
                    
                    var defaultData = {
                        Id: '0',
                        ParentId: parentId || '0',
                        MaterialTypeName: '',
                        Index: '0',
                        IsEnable: false,
                        IsDeleted: false
                    };

                    if (data) {
                        defaultData = {
                            Id: data.id,
                            ParentId: data.parentId,
                            MaterialTypeName: data.materialTypeName,
                            Index: data.index,
                            IsEnable: data.isEnable,
                            IsDeleted: data.isDeleted || false
                        };
                    }

                    form.val('materialTypeForm', defaultData);

                    form.on('submit(submitForm)', function(formData) {
                        event.preventDefault();
                        
                        var submitData = {
                            Id: parseInt(formData.field.Id) || 0,
                            ParentId: parseInt(formData.field.ParentId) || 0,
                            MaterialTypeName: formData.field.MaterialTypeName.trim(),
                            Index: parseInt(formData.field.Index) || 0,
                            IsEnable: formData.field.IsEnable === 'on',
                            IsDeleted: false
                        };
                        
                        var url = data ? '/MaterialType/Update' : '/MaterialType/Add';
                        var token = $('input[name="__RequestVerificationToken"]').val();
                        
                        $.ajax({
                            url: url,
                            type: 'POST',
                            contentType: 'application/json; charset=utf-8',
                            dataType: 'json',
                            data: JSON.stringify(submitData),
                            headers: {
                                'RequestVerificationToken': token
                            },
                            beforeSend: function() {
                                layer.load(2);
                            },
                            success: function(res) {
                                layer.closeAll('loading');
                                if (res.code === 0) {
                                    layer.close(index);
                                    layer.msg('操作成功');
                                    renderTable();
                                } else {
                                    layer.msg('操作失败：' + res.msg);
                                }
                            },
                            error: function(xhr) {
                                layer.closeAll('loading');
                                layer.msg('操作失败，请重试');
                            }
                        });
                        
                        return false;
                    });
                }
            });
        }
    });
</script> 